package com.chang.order.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.chang.common.constant.AuthServerConstant;
import com.chang.common.vo.MemberResponseVo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author: changzhenxi
 * @date: 2025年01月06日 14:17
 * @Version: 1.0
 * @description: 登录拦截器，部分操作需要登录才能进行
 * 之前整合了springSession ，auth模块只要登录成功就会往session中存放登录的用户
 */
@Slf4j
@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberResponseVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri = request.getRequestURI();
        org.springframework.util.AntPathMatcher antPathMatcher = new AntPathMatcher();
        // 为远程调用提供绿色通道,跳过登录检测
        boolean match = antPathMatcher.match("/order/order/status/**", uri);
        boolean match1 = antPathMatcher.match("/alipay/notify", uri);
        boolean match2 = antPathMatcher.match("/alipay/return", uri);
        log.info("order拦截器检测到uri:{}", uri);
        if (match || match1 || match2) {
            return true;
        }

        Object attribute = request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        MemberResponseVo memberResponseVo = new MemberResponseVo();
        BeanUtil.copyProperties(attribute, memberResponseVo);
        if (memberResponseVo.getId() != null) {
            loginUser.set(memberResponseVo);
            return true;
        } else { // 没登陆就去登录
            request.getSession().setAttribute("msg", "你还没登录哦~");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }
    }
}
